/**
 *
 * @type {{mouseInterval: number, pointRange: number, bgColors: Array, isInArea: Polygon.isInArea, checkInUpdateRoutes: Polygon.checkInUpdateRoutes, draw: Polygon.draw, handlePolygonClick: Polygon.handlePolygonClick, handlePolygonDrag: Polygon.handlePolygonDrag}}
 */
var Polygon = {
    mouseInterval:300,
    pointRange:0.02,   //每个区域画线误差范围
    bgColors:CONFIG.routerStrokeColor,   //每条个区域背景图和路线背景图颜色一样
    /**
     * 判断一个点是否在区域内部包括边界
     * @param p
     * @param poly
     * @returns {*}
     */
    isInArea:function (p, poly) {
        var px = p.lat,
            py = Math.abs(p.lng),
            flag = false
        for(var i = 0, l = poly.length, j = l - 1; i < l; j = i, i++) {
                var sx = poly[i].lat,
                    sy = Math.abs(poly[i].lng),
                    tx = poly[j].lat,
                    ty = Math.abs(poly[j].lng);
                // 点与多边形顶点重合
                if ((sx === px && sy === py) || (tx === px && ty === py)) {
                    return "on"
                }
                // 判断线段两端点是否在射线两侧
                if ((sy < py && ty >= py) || (sy >= py && ty < py)) {
                    // 线段上与射线 Y 坐标相同的点的 X 坐标
                    var x = sx + (py - sy) * (tx - sx) / (ty - sy)
                    // 点在多边形的边上
                    if (x === px) {
                        return "on"
                    }
                    // 射线穿过多边形的边界
                    if (x > px) {
                        flag = !flag
                    }
                }

        }
        // 射线穿过多边形边界的次数为奇数时点在多边形内
        return flag ? true : false;
    },


    /**
     * 判断一个点是否在更新的数组里面
     * @param chekcPoint
     * @param updateRoutes
     * @returns {boolean}
     */
    checkInUpdateRoutes:function(chekcPoint,updateRoutes){
            for(var i=0 ;i<updateRoutes.length;i++ ) {
                 if( updateRoutes[i].lat == chekcPoint.lat && updateRoutes[i].lng == chekcPoint.lng){
                     return true;
                 }
            }
            return false;
    },
    getRoutersBgColor( routerId)
    {
        let color = OBJECT.routersBgColorMap[routerId];
        if(!color)
        {
            color = CONFIG.routerStrokeColor.shift();
            OBJECT.routersBgColorMap[routerId] = color;
        }
        return color;
    },
    /**
     * 画多边形
     * @param routers
     * @param map
     * @param routerId
     */
    draw:function (routerId ) {
        if(OBJECT.bermudaTriangle[routerId]) {
              OBJECT.bermudaTriangle[routerId].setMap(null);
              OBJECT.bermudaTriangle[routerId] = null;
        }
        return new Promise(  (resolve , reject)=> {
            let fillColor =   OBJECT.routersBgColorMap[routerId] ;
            let routers = OBJECT.routerEdgePoints[routerId]
          //  Session.getInstance().saveRoutePoints( routerId , routers );
            OBJECT.bermudaTriangle[routerId] = new google.maps.Polygon({
                paths: routers ,
                strokeColor: fillColor,
                strokeOpacity: 0,
                strokeWeight: 0,
                fillColor: fillColor,
                fillOpacity: 0.75,
                editable: true,
                routerId:routerId,
                color:fillColor
            });
            //if(CONFIG.showRouters==false ){
                OBJECT.bermudaTriangle[routerId].setMap(map);
          //  }
            OBJECT.bermudaTriangle[routerId].addListener( 'click', function() {   //鼠标点击区域事件
                Polygon.handlePolygonClick(this)
            })
            OBJECT.bermudaTriangle[routerId].getPaths().forEach(function(path, index){     //每个多边形的路径上设置侦听器
                path.routerId = routerId;
                google.maps.event.addListener(path, 'insert_at', function(){
                    Polygon.handlePolygonDrag( this ,routerId );

                });
                google.maps.event.addListener(path, 'remove_at', function(){
                    Polygon.handlePolygonDrag( this ,routerId );
                });
                google.maps.event.addListener(path, 'set_at', function(){
                    Polygon.handlePolygonDrag( this ,routerId );
                });
            });

            Polygon.setEdgePoints( routerId , routers);   //保存多边形顶点
            CONFIG.drawingRouterEdgePoints=[];  //清空画图顶点数据
            resolve('SUCCESS')
        })

    },
    handlePolygonClick:function (obj) {
        CONFIG.currentOpearateRouterId = obj.routerId;              //设置当前操作的路由id

    },
    handlePolygonDrag:function (obj , routerId) {

        var _this = obj;
        obj.routerId = routerId;
        CONFIG.currentOpearateRouterId = obj.routerId;              //设置当前操作的路由id
        var  afterDrayPointObj = _this.b;
        var afterDrayRouterPoints=[];
        for(var i=0;i<afterDrayPointObj.length;i++){
            var lat = afterDrayPointObj[i].lat().toFixed(CONFIG.latAndLngPrecision);
            var lng = afterDrayPointObj[i].lng().toFixed(CONFIG.latAndLngPrecision);
            var t={lat:Number(lat),lng:Number(lng)}
            afterDrayRouterPoints.push(t)
        }
        afterDrayRouterPoints = qhPlotConvexHull(afterDrayRouterPoints);
        Polygon.setEdgePoints(routerId , afterDrayRouterPoints );
        CONFIG.optimizeOrderpoints[routerId] = true;
        Queue( routerId )
      //  showLoading();
        //CONFIG.optimizeOrderpoints[routerId] = true;
        //Server.getInstance().assignPointToPolygon();
        //Router.getInstance().calculateRouterInfo(routerId);

    },
    /**
     *
     * @param routerId
     * @param points
     */
    setEdgePoints:function(routerId, points)
    {

        OBJECT.routerEdgePoints[routerId] = points;
    },
    getPolygonColor:function()
    {

    },
    /**
     * 从地图上移除一个多边形
     * @param routerId
     */
    removePloygonFromMap( routerId)
    {
        OBJECT.bermudaTriangle[routerId].setMap( null );
    },
    /**
     * 移除所有多边形
     */
    removeAllPloygon()
    {

          for(let index in OBJECT.bermudaTriangle)
          {
              OBJECT.bermudaTriangle[index].setMap( null );
          }
    },
    /**
     * 显示所有多边形
     */
    showAllPloygon()
    {
        for(let index in OBJECT.bermudaTriangle)
        {
            OBJECT.bermudaTriangle[index].setMap( map );
        }
    }
    ,
    /**
     * 删除所有的多变形数据
     */
    deleteAllPloygon()
    {
        this.removeAllPloygon()
        OBJECT.bermudaTriangle=[];
    }
    };
